package com.glsc.ngateway.oaflow.amqp;

import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.base.domain.mysql.gateway.oaflow.TFixedincomeProcess;
import com.glsc.ngateway.common.base.domain.mysql.gateway.oaflow.TOaFlowMessageTable;
import com.glsc.ngateway.common.base.repo.mysql.gateway.oaflow.TFixedincomeProcessRepository;
import com.glsc.ngateway.common.base.repo.mysql.gateway.oaflow.TOaFlowMessageTableRepository;
import com.glsc.ngateway.oaflow.service.FixedIncomeService;
import com.glsc.ngateway.oaflow.service.FlowService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
public class FixedIncomeOaReceiver {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String fixedIncomeQueue = "gateway.queue.fwFlow.fixedincome";
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    FixedIncomeService fixedIncomeService;
    @Autowired
    TFixedincomeProcessRepository tFixedincomeProcessRepository;
    @Autowired
    FlowService flowService;
    @Autowired
    TOaFlowMessageTableRepository tOaFlowMessageTableRepository;

    private static final String OA_REVIEW_PASS = "1";

    private static final String OA_REVIEW_GOING = "0";

    private static final String OA_REVIEW_NODE_END_STATE = "3";

    private static final String OA_REVIEW_NODE_NAME_FORCE_END = "强制归档";
    private static final String OA_REVIEW_NODE_NAME_END = "结束";
    private static final String OA_REVIEW_NODE_NAME_9_REVIEW = "公司相关部门委员发表意见";


    private static final String DESCRIPTION_REJECT = "退回";
    private static final String DESCRIPTION_AGREE = "流程结束";
    /*流程节点状态（实际仅中文名称）
    1.发起人
    2.资管产品委委员发表意见
    3.发起人回复意见
    4.资管产品委委员确认意见
    5.资管部负责人
    6.发起人更新材料
    8.内控部审核
    9.公司相关部门委员发表意见
    10.发起人回复意见
    11.公司相关部门委员确认意见
    12.结束
    */
    /*
     * 查询OA表单数据返回样例：
     * {"requestId":"621896","description":"success","workflowName":"（2021-85）国联悦享优选/尊选/精选系列FOF单一资产管理计划变更评审","workflowId":"174103"},SynOaReviewStatusDto(workflowId=174103, requestId=621896, productSelect=1002426, flowStatusType=1, flowStatus=null, reviewerReplyCode=1, reviewerReply=表决已全票“同意", depReviewerReplyCode=null, depReviewerReply=null, businessTypeCode=0, businessType=单一非标类, flowNodeCode=196946, flowNode=资管部负责人)
     * */

    /**
     * JSON格式：workflowId:111,requestId:123456789,workflowName:测试流程标题,description:success
     */
    @RabbitListener(queues = {fixedIncomeQueue})
    @RabbitHandler
    public void processMessage(Message messageObject) throws IOException, NoSuchFieldException, IllegalAccessException {
        try {
            String message = new String(messageObject.getBody());
            logger.info("gateway.queue.fwFlow.fixedincome，消息队列收到消息，message receiver:" + message);
            JSONObject msgJsonObject = JSONObject.parseObject(message);
            //流程节点变化，获取事件通知时，主动延迟再去获取表单数据，待网关延迟功能上线后，此处不需要再延迟消费
//            try {
//                Thread.sleep(5 * 1000);//
//            } catch (InterruptedException e) {
//                logger.error("流程节点变化，获取事件通知时，主动延迟再去获取表单数据sleep失败", e);
//            }
            //end of===========================
            String workflowId = msgJsonObject.getString("workflowId");
            String requestId = msgJsonObject.getString("requestId");
            String workflowName = msgJsonObject.getString("workflowName");
            String description = msgJsonObject.getString("description");
            TOaFlowMessageTable flowMessage = new TOaFlowMessageTable(workflowId, workflowName, requestId, description);
            tOaFlowMessageTableRepository.save(flowMessage);

            //获取流程当前状态
//        requestStatus -> 结束
//            Map<String, Object> flowCurrentStatus = flowService.getWorkFlowCurrentStatus(Integer.parseInt(requestId));
//            //获取流程要素明细
//            Map<String, Object> flowdetail = flowService.getWorkFlowInfos(Integer.parseInt(requestId));
//            List<WorkflowRequestlog> flowinfos = (List<WorkflowRequestlog>) flowdetail.get("flowInfos");
//            WorkflowRequestlog w = flowinfos.get(0);
//            String remark = w.getRemark();

            List<TFixedincomeProcess> list = tFixedincomeProcessRepository.findByRequestId(requestId);
            if (list != null && list.size() > 0) {
//                if (flowCurrentStatus.get(OaflowResponse.requestStatus).equals(OA_REVIEW_NODE_NAME_END)) {
                if (DESCRIPTION_AGREE.equals(description)) {
                    //结束，批准的结束
                    //1.网关直接置位
                    for (TFixedincomeProcess process : list) {
                        process.setStatus("1");
                        process.setOaStatus("1");
                        tFixedincomeProcessRepository.save(process);
                    }
                } else if (DESCRIPTION_REJECT.equals(description)) {
                    //拒绝
                    //1.网关直接置位
                    for (TFixedincomeProcess process : list) {
                        process.setStatus("2");
                        process.setOaStatus("1");
                        tFixedincomeProcessRepository.save(process);
                    }
                } else {
                    logger.error("衡泰移动审批，oa审批调用网关接口，返回description不是（流程结束或者退回），不需要处理返回。msg=" + message);
                }
            }
        } catch (Exception e) {
            logger.error("衡泰移动审批，消费消息队列异常", e);
        }
    }


    /*
     * 调用OA查询表单数据
     * OA接口正常返回：
     * {"code":0,"data":[{"flowNodeCode":1106974,"flowNode":"结束","requestId":464981,"flowInfos":{"ID":24,"applyNumber":"zgcppslc20210600024","applyDate":"2021-06-10","applicant":"杨昳,yiyang@glsc.com.cn","applicantDepart":"资产管理部/运营管理-运营","applicantComp":"国联证券总部","businessType":"集合标类","productSelect":"1000241","reviewer":"张春蓉","depReviewer":"杨昳","reviewerReply":"发起人意见落实回复","depReviewerReply":"表决已全票“同意”","businessTypeCode":2,"reviewerReplyCode":0,"depReviewerReplyCode":1},"flowStatusType":"3"}],"status":"SUCCESS"}
     * OA接口异常返回数据：
     * {"status":"EXCEPTION","code":17,"msg":"业务异常，查询结果为NULL"}
     * */
//    private SynOaReviewStatusDto getOAFormData(String workflowId, String requestId) throws NoSuchFieldException, IllegalAccessException {
//        Map<String, Object> retStr = flowService.getWorkFlowCurrentStatus(Integer.parseInt(requestId));
//        logger.info("调用OA查询表单数据返回:" + retStr);
//
//        JSONObject retJSONObject = JSONObject.parseObject(retStr);
//
//        if (ToolUtils.isEmpty(retStr) || retJSONObject == null || !"success".equals(retJSONObject.get("code"))) {
//            String errMsg = MessageFormat.format("查询表单数据失败，查询表单workflowId={0}-requestId={1}，接口返回异常：{2}", workflowId, requestId, retStr);
//            logger.error(errMsg);
//            throw AmException.error(errMsg);
//        }
//
//        //同步OA评审流程状态工作流编号列表
//        String idList = systemConfigService.findConfigValueByCode(Constant.CONFIG_KEY_SYNC_OA_REVIEW_STATUS_ID_LIST);
//        //查询OA表单数据字段
//        String fieldList = systemConfigService.findConfigValueByCode(Constant.CONFIG_KEY_SYNC_OA_FORM_DATA_FIELD);
//        SynOaReviewStatusDto synOaReviewStatusDto = new SynOaReviewStatusDto();
//        synOaReviewStatusDto.setWorkflowId(workflowId);
//        synOaReviewStatusDto.setRequestId(requestId);
//
//
//        JSONArray dataJson = retJSONObject.getJSONArray("data");
//        JSONObject jsonObject = dataJson.getJSONObject(0);
//        JSONObject flowInfosJSONObject = jsonObject.getJSONObject("flowInfos");//表单个性化字段信息
//
//        //表单公共字段解析
//        Integer flowNodeCode = jsonObject.getInteger("flowNodeCode");
//        synOaReviewStatusDto.setFlowNodeCode(flowNodeCode);
//
//        String workflowName = retJSONObject.getString("workflowName");
//        if (ToolUtils.isNotEmpty(workflowName)) {
//            synOaReviewStatusDto.setWorkflowName(workflowName);
//        }
//        String flowNode = jsonObject.getString("flowNode");
//        if (ToolUtils.isNotEmpty(flowNode)) {
//            synOaReviewStatusDto.setFlowNode(flowNode);
//        }
//
//
//        logger.info("获取OA表单，返回synOaReviewStatusDto:" + synOaReviewStatusDto);
//        return synOaReviewStatusDto;
//    }

    /**
     * 流程实例Id合并
     *
     * @param existRequestIdStr 现有流程实例字符串，多个逗号分割
     * @param newRequestId      新流程实例Id
     * @return
     */
//    public String mergeRequestIdList(String existRequestIdStr, String newRequestId) {
//        String mergeRequestIdStr = null;
//        if (StrUtil.isEmpty(existRequestIdStr)) {
//            mergeRequestIdStr = newRequestId == null ? "" : StrUtil.trim(newRequestId);
//        } else {
//            List<String> existRequestIdList = Arrays.asList(existRequestIdStr.split(","));
//            if (!existRequestIdList.contains(newRequestId)) {
//                existRequestIdList.add(newRequestId);
//            }
//
//            mergeRequestIdStr = String.join(",", existRequestIdList);
//        }
//
//        if (StrUtil.isEmpty(mergeRequestIdStr)) {
//            mergeRequestIdStr = "";
//        }
//
//        return mergeRequestIdStr;
//    }
}
